﻿using MediatR;
using SheepCultivation.Common.Domain;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;

namespace SheepCultivation.API.AddliCation.EnterPriseW
{
    public class EnterPriseCreateHandler : IRequestHandler<EnterPriseCreateCommon, Result>
    {
        public readonly IBaseRepository<Enterprise> EnterpriseRepository;
        public readonly IBaseRepository<EnterPriseTree> EnterPriseTreeRepository; 
        public readonly ILogger<EnterPriseCreateHandler> logger;

        public EnterPriseCreateHandler(IBaseRepository<Enterprise> enterpriseRepository, IBaseRepository<EnterPriseTree> enterPriseTreeRepository, ILogger<EnterPriseCreateHandler> logger)
        {
            EnterpriseRepository = enterpriseRepository;
            EnterPriseTreeRepository = enterPriseTreeRepository;
            this.logger = logger;
        }

        public async Task<Result> Handle(EnterPriseCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.error };
            try
            {
                logger.LogInformation("企业信息新增");
                var res = new Enterprise()
                {
                    EnterpriseName = request.EnterpriseName,
                    Enterpriseillustrate = request.Enterpriseillustrate,
                    EnterpriseLogo = request.EnterpriseLogo,
                    IndustryId1 = request.IndustryId1,
                    IndustryId2 = request.IndustryId2,
                    ProvinceId = request.ProvinceId,
                    CityId = request.CityId,
                    CountyId = request.CountyId,
                    FullAddress = request.FullAddress,
                    EnterprisePhone = request.EnterprisePhone,
                    Unifiedsocialcode = request.Unifiedsocialcode,
                    Description = request.Description,
                    Deactivated = false,
                    Head = request.Head,
                    FinanceHead = request.FinanceHead,
                    ApartHead = request.ApartHead,
                    MyProperty = 1,
                    AccountingunitId1 = request.AccountingunitId1,
                    AccountingunitId2 = request.AccountingunitId2
                };
                EnterpriseRepository.Add(res);

                var EnterPriseTreeTable = new EnterPriseTree()
                {
                    unitName = res.EnterpriseName,
                    Pid=0
                };
                EnterPriseTreeRepository.Add(EnterPriseTreeTable);
                result.Code = (int)CommonEnumCode.success;
                result.Msg = "企业信息新增";
            }
            catch (Exception ex)
            {
                logger.LogError("企业信息新增失败" + ex.Message);
                result.Msg = "企业信息新增失败";
            }
            return result;
        }
    }
}
